import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import {Card, Table, Row, Col, Button, Spin} from 'antd';
import {DATE_FORMAT, DATETIME_FORMAT, TABLE} from '../constants';
import {formatDateTime, conventEnumValueToString, formatAmount, formatPercent} from '../utils';
import {saleOrderStatus} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
export class Detail extends React.PureComponent {
    state = {
        loading: false
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleConfirmClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickConfirm().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSubmitClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    render() {
        const {options, details = [], shipmentDetails = []} = this.props.detail;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(options, PERMISSION.submit))
            operations.push(
                <WrappedPopconfirm
                    id="submit"
                    key="submit"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleSubmitClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detail.popconfirm.save',
                            defaultMessage: '保存'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.assistSubmit) && hasPermissions(options, PERMISSION.assistSubmit))
            operations.push(
                <WrappedPopconfirm
                    id="assistSubmit"
                    key="assistSubmit"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleSubmitClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.assistSubmit',
                            defaultMessage: '代提交'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(options, PERMISSION.confirm))
            operations.push(
                <WrappedPopconfirm
                    id="confirm"
                    key="confirm"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleConfirmClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.confirm',
                            defaultMessage: '确认'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.return) && hasPermissions(options, PERMISSION.return))
            operations.push(
                <Button key="return" href={`#${routes.return.format(this.props.id)}`} className={styles.btnMargin} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.returnOrder',
                        defaultMessage: '退回'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(
                <Button key="update" href={`#${routes.update.format(this.props.id)}`} className={styles.btnMargin} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.assistUpdate) && hasPermissions(options, PERMISSION.assistUpdate))
            operations.push(
                <Button key="assistUpdate" href={`#${routes.assistUpdate.format(this.props.id)}`} className={styles.btnMargin} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.assistUpdate',
                        defaultMessage: '代编辑'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.assistAbandon) && hasPermissions(options, PERMISSION.assistAbandon))
            operations.push(
                <WrappedPopconfirm
                    id="assistAbandon"
                    key="assistAbandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.assistAbandon',
                            defaultMessage: '代作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.planQuantity',
                    defaultMessage: '订货数量'
                }),
                dataIndex: 'planQuantity'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.taxPrice',
                    defaultMessage: '含税价格'
                }),
                dataIndex: 'taxPrice',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.totalTaxPrice',
                    defaultMessage: '订货金额'
                }),
                dataIndex: 'totalTaxPrice',
                className: styles.textAlign,
                render: (text, record) => {
                    const {taxPrice = 0, planQuantity = 0} = record;
                    return formatAmount(taxPrice * planQuantity);
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize'
            }
        ];
        const shipmentColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.code',
                    defaultMessage: '发运单号'
                }),
                dataIndex: 'code'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.shipQuantity',
                    defaultMessage: '发运数量'
                }),
                dataIndex: 'shipQuantity'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detail.colums.confirmQuantity',
                    defaultMessage: '确认数量'
                }),
                dataIndex: 'confirmQuantity'
            }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card>
                        <DescriptionList
                            size="large"
                            title={<Row>
                                <Col span={6}>
                                    {this.props.intl.formatMessage({
                                        id: 'detail.card.title',
                                        defaultMessage: '单据信息'
                                    })}
                                </Col>
                                <Col className={styles.textAlign} span={18}>
                                    {operations}
                                </Col>
                            </Row>}>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.code',
                                    defaultMessage: '订单编号'
                                })}>
                                {this.props.detail.code}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.dealerName',
                                    defaultMessage: '总代'
                                })}>
                                {this.props.detail.dealerName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.typeName',
                                    defaultMessage: '订单类型'
                                })}>
                                {this.props.detail.typeName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.status',
                                    defaultMessage: '状态'
                                })}>
                                {conventEnumValueToString(saleOrderStatus, this.props.detail.status)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.requiredArrivedDate',
                                    defaultMessage: '要求到货日期'
                                })}>
                                {formatDateTime(this.props.detail.requiredArrivedDate, DATE_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.raisingRate',
                                    defaultMessage: '加价率'
                                })}>
                                {formatPercent(this.props.detail.raisingRate)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.totalFee',
                                    defaultMessage: '总金额'
                                })}>
                                {formatAmount(this.props.detail.totalFee)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.creditCode',
                                    defaultMessage: '销售凭证编号'
                                })}>
                                {this.props.detail.creditCode}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.creditDescribe',
                                    defaultMessage: '销售凭证描述'
                                })}>
                                {this.props.detail.creditDescribe}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.orderReasonCode',
                                    defaultMessage: '订购原因编号'
                                })}>
                                {this.props.detail.orderReasonCode}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.orderReason',
                                    defaultMessage: '订购原因描述'
                                })}>
                                {this.props.detail.orderReason}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.warehouseName',
                                    defaultMessage: '发货仓库'
                                })}>
                                {this.props.detail.warehouseName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.creatorName',
                                    defaultMessage: '创建人'
                                })}>
                                {this.props.detail.creatorName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.createTime',
                                    defaultMessage: '创建日期'
                                })}>
                                {formatDateTime(this.props.detail.createTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.modifierName',
                                    defaultMessage: '修改人'
                                })}>
                                {this.props.detail.modifierName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.modifyTime',
                                    defaultMessage: '修改日期'
                                })}>
                                {formatDateTime(this.props.detail.modifyTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.submitterName',
                                    defaultMessage: '提交人'
                                })}>
                                {this.props.detail.submitterName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.submitTime',
                                    defaultMessage: '提交时间'
                                })}>
                                {formatDateTime(this.props.detail.submitTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.confirmorName',
                                    defaultMessage: '确认人'
                                })}>
                                {this.props.detail.confirmorName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.confirmTime',
                                    defaultMessage: '确认时间'
                                })}>
                                {formatDateTime(this.props.detail.confirmTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.abandonerName',
                                    defaultMessage: '作废人'
                                })}>
                                {this.props.detail.abandonerName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.abandonTime',
                                    defaultMessage: '作废时间'
                                })}>
                                {formatDateTime(this.props.detail.abandonTime, DATETIME_FORMAT)}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.returnerName',
                                    defaultMessage: '回退人'
                                })}>
                                {this.props.detail.returnerName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.returnTime',
                                    defaultMessage: '回退时间'
                                })}>
                                {formatDateTime(this.props.detail.returnTime, DATETIME_FORMAT)}
                            </Description>
                        </DescriptionList>
                        <DescriptionList col={1} size="large">
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'detail.info.remark',
                                    defaultMessage: '备注'
                                })}>
                                {this.props.detail.remark}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detail.details.title',
                            defaultMessage: '清单'
                        })}
                        bordered={false}>
                        <Table className="white-space-nowrap" rowKey="partId" columns={columns} pagination={false} dataSource={details} {...TABLE} />
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detail.shipmentDetails.title',
                            defaultMessage: '交货清单'
                        })}
                        bordered={false}>
                        <Table className="white-space-nowrap" rowKey="partId" columns={shipmentColumns} pagination={false} dataSource={shipmentDetails} {...TABLE} />
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.return',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
Detail.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickConfirm: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {getDetail, clearData, onClickAbandonForDetail, onClickConfirmForDetail, onClickSubmitForDetail, querySearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    detail: getDetailData(state),
    permissions: getPermissions(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser'])
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(querySearch());
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickConfirm: () =>
        dispatch(onClickConfirmForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(querySearch());
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickSubmit: () =>
        dispatch(onClickSubmitForDetail(ownProps.id)).then(success => {
            if(success) {
                dispatch(querySearch());
                ownProps.history.push(routes.query.url());
            }

            return success;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Detail));
